import { useMemoizedFn } from 'ahooks';
import { Segmented, Switch } from 'antd';
import React, { Dispatch, useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import { SvgIcon } from '@/components/icon';
import { t } from '@/locales/i18n';
import { AppContext } from '@/pages/app/detail/context';
import BasicInfo from '@/pages/app-orchestration/components/BasicInfo';
import HotQuestionModal from '@/pages/app-orchestration/components/HotQuestionModal';
import InputGuideModal from '@/pages/app-orchestration/components/InputGuideModal';
import {
  defaultChatInputGuideConfig,
  defaultHotQuestionConfig,
  defaultWhisperConfig,
} from '@/pages/chat/tools/constants';
import { HotQuestion, InputGuide, useOrchestrationStore } from '@/store/orchestrationStore';
import { AppChatConfigType, AppDetailType, VariableItemType } from '@/types/app/type';
import { FlowNodeTypeEnum } from '@/types/workflow/constant';
import { getAppChatConfig } from '@/types/workflow/utils';

import { WorkflowContext } from '../../context';

import VariableEdit from './system/VariableEdit';
import WelcomeTextConfig from './system/WelcomeTextConfig';

type ComponentProps = {
  chatConfig: AppChatConfigType;
  setAppDetail: Dispatch<React.SetStateAction<AppDetailType>>;
};

function NodeUserGuide({ onClose }: { onClose: () => void }) {
  const { appDetail, preview, setAppDetail } = useContextSelector(AppContext, (v) => v);
  const { nodeList } = useContextSelector(WorkflowContext, (v) => v);
  const data = nodeList.find((v) => v.flowNodeType === FlowNodeTypeEnum.systemConfig);
  const { inputGuides, hotQuestions } = useOrchestrationStore();
  const [activeTab, setActiveTab] = useState<'basic' | 'advanced'>('basic');

  const chatConfig = useMemo<AppChatConfigType>(() => {
    return getAppChatConfig({
      chatConfig: appDetail.chatConfig,
      systemConfigNode: data,
      isPublicFetch: true,
    });
  }, [data, appDetail]);

  const componentsProps = useMemo(
    () => ({
      chatConfig,
      setAppDetail,
    }),
    [chatConfig, setAppDetail],
  );

  const isChatConfigSet = useMemo(() => {
    return (
      appDetail.chatConfig?.welcomeText ||
      appDetail.chatConfig?.chatInputGuide ||
      appDetail.chatConfig?.hotQuestionConfig ||
      appDetail.chatConfig?.whisperConfig ||
      (appDetail.chatConfig?.variables && appDetail.chatConfig.variables.length > 0)
    );
  }, [appDetail.chatConfig]);

  return (
    <div className="relative h-[calc(100vh-110px)] w-[25%] min-w-[380px] max-w-[380px] p-2 transition-all duration-300">
      <Segmented
        block
        onChange={(value) => {
          setActiveTab(value as 'basic' | 'advanced');
        }}
        className="custom-segmented h-[74px]"
        options={[
          {
            label: (
              <div className="flex flex-col items-center gap-1">
                <SvgIcon icon="menu-entry" size={20} color="var(--brand-color)" />
                <div className="text-sm text-@brand-color">基础设置</div>
              </div>
            ),
            value: 'basic',
          },
          {
            label: (
              <div className="group flex flex-col items-center gap-1">
                {isChatConfigSet ? (
                  <SvgIcon icon="workflow-basic-config" size={20} color="var(--brand-color)" />
                ) : (
                  <SvgIcon icon="workflow-basic" size={20} />
                )}
                <div className={`text-sm ${isChatConfigSet ? 'text-@brand-color' : ''}`}>
                  高级设置
                </div>
              </div>
            ),
            value: 'advanced',
          },
        ]}
      />
      {activeTab === 'basic' && (
        <div className="h-full w-full">
          <BasicInfo isPreview={preview} isWorkflow className="max-h-[calc(100vh-200px)]" />
        </div>
      )}
      {activeTab === 'advanced' && (
        <div
          style={{
            transition: 'all 1s ease-in-out',
            maxHeight: 'calc(100vh - 200px)',
            overflowY: 'auto',
          }}
          className={`mt-4 flex flex-col gap-4 ${preview ? 'pointer-events-none' : ''} pr-2`}
        >
          <div className="flex h-[40px] items-center gap-1 rounded-lg bg-@brand-color-light px-[16px] py-[9px] text-sm">
            <SvgIcon icon="info-circle" color="var(--brand-color)" size={16} />
            <span className="text-text-5">可配置应用的基础信息与系统设置</span>
          </div>
          <div className="rounded-2xl">
            <WelcomeText {...componentsProps} />
          </div>

          <div className="flex items-center rounded-md bg-bg-1 p-2">
            <VoiceGuide {...componentsProps} />
          </div>

          <div className="flex items-center rounded-md bg-bg-1 p-2">
            <QuestionGuide {...componentsProps} />
          </div>

          <div className="flex items-center rounded-md bg-bg-1 p-2">
            <HotQuestionGuide {...componentsProps} hotQuestions={hotQuestions} />
          </div>

          <div className="flex items-center rounded-md bg-bg-1 p-2">
            <QuestionInputGuide {...componentsProps} inputGuides={inputGuides} />
          </div>

          <div className="items-center rounded-2xl">
            <ChatStartVariable {...componentsProps} />
          </div>
        </div>
      )}
    </div>
  );
}

export default React.memo(NodeUserGuide);

function WelcomeText({ chatConfig: { welcomeText }, setAppDetail }: ComponentProps) {
  const [value, setValue] = useState(welcomeText);
  return (
    <div className="nodrag">
      <WelcomeTextConfig
        // resize={'both'}
        value={value}
        onChange={(e) => {
          const text = e.target.value;
          setValue(text);
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              welcomeText: text,
            },
          }));
        }}
      />
    </div>
  );
}

function ChatStartVariable({ chatConfig: { variables = [] }, setAppDetail }: ComponentProps) {
  const updateVariables = useMemoizedFn((value: VariableItemType[]) => {
    setAppDetail((state) => ({
      ...state,
      chatConfig: {
        ...state.chatConfig,
        variables: value,
      },
    }));
  });

  return (
    <VariableEdit
      headerClassName="rounded-md bg-bg-1 pl-3 pr-2 py-1"
      variables={variables}
      onChange={(e) => updateVariables(e)}
    />
  );
}

function QuestionGuide({ chatConfig: { questionGuide = false }, setAppDetail }: ComponentProps) {
  return (
    <div className="flex w-full items-center justify-between">
      <div className="ml-2 flex items-center gap-2">
        {/* <SvgIcon icon="rj-guess" /> */}
        <span className="text-sm">{t('core.app.Question Guide')}</span>
      </div>
      <Switch
        checked={questionGuide}
        onChange={(e) => {
          const value = e;
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              questionGuide: value,
            },
          }));
        }}
      />
    </div>
  );
}

function VoiceGuide({ chatConfig: { whisperConfig, ttsConfig }, setAppDetail }: ComponentProps) {
  return (
    <div className="flex w-full items-center justify-between">
      <div className="ml-2 flex items-center gap-2">
        {/* <SvgIcon icon="ic_rj_sound" /> */}
        <span className="text-sm">语音</span>
      </div>
      <Switch
        className="ml-auto"
        checked={whisperConfig?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              whisperConfig: {
                ...(whisperConfig || defaultWhisperConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
    </div>
  );
}

function QuestionInputGuide({
  chatConfig: { chatInputGuide },
  setAppDetail,
  inputGuides,
}: ComponentProps & { inputGuides: InputGuide[] }) {
  const appId = useContextSelector(WorkflowContext, (v) => v.appId);
  const updateInputGuides = useContextSelector(WorkflowContext, (v) => v.updateInputGuides);
  const [isPreview, setIsPreview] = useState(false);
  const [inputGuideModalVisible, setInputGuideModalVisible] = useState(false);

  const closeInputGuideModal = () => {
    setInputGuideModalVisible(false);
  };

  const saveInputGuides = (guides: InputGuide[]) => {
    updateInputGuides(guides);
  };

  const openInputGuideModal = () => {
    setInputGuideModalVisible(true);
  };

  return appId ? (
    <div className="flex w-full items-center justify-between">
      <div className="ml-2 flex items-center gap-2">
        {/* <SvgIcon icon="ic_mail" /> */}
        <span className="text-sm">{t('input_guide')}</span>
      </div>
      <span
        className={`mr-2 text-[14px] text-[#86909C] ${
          isPreview ? 'cursor-default' : 'cursor-pointer hover:text-[#1677ff]'
        }`}
        onClick={() => !isPreview && openInputGuideModal()}
      >
        已配置{inputGuides.length}个引导&gt;&gt;
      </span>
      <Switch
        className="ml-auto"
        checked={chatInputGuide?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              chatInputGuide: {
                ...(chatInputGuide || defaultChatInputGuideConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
      <InputGuideModal
        visible={inputGuideModalVisible}
        onClose={closeInputGuideModal}
        initialGuides={inputGuides}
        onSave={saveInputGuides}
      />
    </div>
  ) : null;
}

function HotQuestionGuide({
  chatConfig: { hotQuestionConfig },
  setAppDetail,
  hotQuestions,
}: ComponentProps & { hotQuestions: HotQuestion[] }) {
  const appId = useContextSelector(WorkflowContext, (v) => v.appId);
  const updateHotQuestions = useContextSelector(WorkflowContext, (v) => v.updateHotQuestions);
  const [isPreview, setIsPreview] = useState(false);
  const [hotQuestionModalVisible, setHotQuestionModalVisible] = useState(false);

  const closeHotQuestionModal = () => {
    setHotQuestionModalVisible(false);
  };

  const saveHotQuestions = (hotQuestions: HotQuestion[]) => {
    updateHotQuestions(hotQuestions);
  };

  const openHotQuestionModal = () => {
    setHotQuestionModalVisible(true);
  };

  return appId ? (
    <div className="flex w-full items-center justify-between">
      <div className="ml-2 flex items-center gap-2">
        {/* <SvgIcon icon="point-all" /> */}
        <span className="text-sm">热门问题</span>
      </div>
      <span
        className={`mr-2 text-[14px] text-[#86909C] ${
          isPreview ? 'cursor-default' : 'cursor-pointer hover:text-[#1677ff]'
        }`}
        onClick={() => !isPreview && openHotQuestionModal()}
      >
        已配置{hotQuestions?.length}个问题&gt;&gt;
      </span>
      <Switch
        className="ml-auto"
        checked={hotQuestionConfig?.open ?? false}
        onChange={(e) => {
          setAppDetail((state) => ({
            ...state,
            chatConfig: {
              ...state.chatConfig,
              hotQuestionConfig: {
                ...(hotQuestionConfig || defaultHotQuestionConfig),
                open: !!e,
              },
            },
          }));
        }}
      />
      <HotQuestionModal
        visible={hotQuestionModalVisible}
        onClose={closeHotQuestionModal}
        initialQuestions={hotQuestions}
        onSave={saveHotQuestions}
      />
    </div>
  ) : null;
}
